<?php
namespace app\controller;

use app\BaseController;
use app\controller\model;
use liliuwei\think\Auth;
use think\facade\Session;
use think\facade\Db;
class ApiMini extends BaseController
{
    protected $getpath="",$token,$nowTime,$model,$tables,$service,$user,$userID;
    protected $gobaluser="";
	protected $notify = "https://gas.zhissf.com/Notify";
    public function __construct(){
	    $this->token = request()->param("token");
	    $this->getPath = strtolower(request()->controller()) . "/" . strtolower(request()->action());
	    $this->nowTime = date("Y-m-d H:i:s");
	    $this->tables = new model\Tables();
	    $inArr = ['wxlogin','getconfig','getarticleinfo','getnoticelist2','getlist'];
		if(!in_array(strtolower(request()->action()),$inArr)  || strlen($this->token)==32){
			$this->check_token();
		}
    }
	public function getMyInfo(){
		echojson([
			'volume'=>number_format($this->user['volume'],2),
			'amount'=>number_format($this->user['amount'],2),
			'subPrice'=>number_format($this->user['subPrice'],2),
			'payPrice'=>number_format($this->user['payPrice'],2),
		]);
	}
	public function postReturn(){
		$orderID = request()->param("orderID");
		$cause = request()->param("cause");
		$amount = request()->param("amount");
		$content = request()->param("content");
		lock();
		$order = DB::name($this->tables->orders)->lock(true)->where("id",$orderID)->find();
		if(!$order)echojson([],1,'ID错误');
		if($order['status']<3)echojson([],1,'未支付');
		if($order['reOrder']==1)echojson([],1,'已在退款中');
		if($order['reOrder']==2)echojson([],1,'已完成退款');
		if($order['payPrice']<$amount)echojson([],1,'金额过大');
		$order = DB::name($this->tables->orders)->where("id",$orderID)->update(['reOrder'=>1,'cause'=>$cause,'content'=>$content,'reMoney'=>$amount]);
		if(!$order)echojson([],1,'发起失败');
		echojson();
	}
	public function postOrder(){
		$id = request()->param("id");
		$amount = request()->param("amount");
		$amount2 = request()->param("amount2");
		$sale = request()->param("sale");
		$oil_gun = request()->param("oil_gun");
		$oil_no = request()->param("oil_no");
		if($amount <= 0)echojson([],1,'总金额错误');
		if($oil_gun <= 0)echojson([],1,'未选择枪号');
		$gas = DB::name($this->tables->gas)->where("id",$id)->find();
		if(!$gas)echojson([],1,'油站ID错误');
		if($gas['status'] != 1)echojson([],1,'油站未营业');
		$gasModel = new model\Gas($gas['id'],[],$gas);
		$gasModel->getGasPrice(true);
		$gas['prices'] = $gasModel->getWeekPrice();
		$price_yfq = 0;
		$price_gun = 0;
		foreach ($gas['prices'] as $v){
			if($v['oil_no'] == $oil_no){
				$gas['prices'] = $v;
				$price_yfq = $v['price_yfq'];
				$price_gun = $v['price_gun'];
				break;
			}
		}
		if($price_yfq <= 0)echojson([],1,'获取价格错误');
		if($price_yfq > $price_gun)echojson([],1,'价格错误');
		$volume = bcdiv($amount,$price_gun,10);
		$cha = bcsub($price_gun,$price_yfq,2);
		$sale2 = sishewuru(bcmul($volume,$cha,10));//round四舍五入2位数
		$amount2_2 = sishewuru(bcsub($amount,$sale2,10));
		$volume = sishewuru($volume);//round四舍五入2位数

		//价格浮动判断 冗余判断 在冗余范围内 以用户端显示的价格为准
		$priceAddSub = r_rule2(277)['rule'];
		$priceAddSub = str_replace("，",",",$priceAddSub);
		$priceAddSub = explode(",",$priceAddSub);
		if(is_array($priceAddSub) && count($priceAddSub)==2){
//			if($sale2 != $sale)echojson([],800,'价格变动 请重新下单');
			if($amount2_2 != $amount2){
				if(bcsub($amount2,$priceAddSub[1],2) > $amount2_2)echojson([],800,'价格变动 请重新下单');
				if(bcadd($amount2,$priceAddSub[0],2) < $amount2_2)echojson([],800,'价格变动 请重新下单');
			}
		}else{
			if($amount2 != $amount2_2)echojson([],800,'价格变动 请重新下单');
		}
		//上游查询优惠
		//---------------------暂时不用上游查询
		//发送上游预下单
		$order_id = "JCH20240925005228534";  //上游返回的订单号
		//创建本地订单
		$orderNo = getOrderNo();
		if(in_array($gas['fromID'],[4])){ //4嗨加油
			//没返回 直接用$orderNo
			$order_id = $orderNo ;
		}
		$orderArr=[
			'uid'=>$this->userID,
			'order_no'=>$orderNo,
			'supplierID'=>$gas['fromID'],
			'supplier_no'=>$order_id,
			'gasID'=>$id,
			'oil_no'=>$oil_no,
			'oil_gun'=>$oil_gun,
			'amount'=>$amount,
			'volume'=>$volume,
			'sale'=>$sale,
			'payPrice'=>$amount2,//加了冗余 就用用户显示的价格为准
			'addTime'=>nowTime(),
			'endTime'=>time()+1800,
		];
		//创建本地订单结束
		//上游注册订单 支付成功后再上游注册
//		$supplierModel = new model\Supplier($gas['fromID']);
//		$supplierOrder = $supplierModel->mkOrder($orderArr);
//		if($supplierOrder!==true)echojson([],1,''.$supplierOrder);
		//创建支付订单
//		$amount2=0.01;
		$payModel = new model\SPay();
		$order = $payModel->create('wx_lite',$orderArr['order_no'],$amount2,$gas['name'].'加油',['appid'=>$this->tables->wxAppID,'openid'=>$this->user['openid']],$this->notify);
		if(isset($order['resultCode']) && $order['resultCode']=='SUCCESS'){
			$orderArr['pay_no'] = $order['transactionId'];
			$orderArr['payJson'] = json_encode($order);
			$orderArr['status'] = 2;
			$up = DB::name($this->tables->orders)->insertGetId($orderArr);
			if($up)echojson($order['payInfo'],0,$up);
		}
//		"payInfo" => "{"timeStamp":"1749130841","package":"prepay_id=wx05214041805178083271369f93c3ac0001","paySign":"FHTLgTyM3JDny1QTkjoBbCnmYwgIv68uKDtrA/vAXlrzyNV8Lhbt0omlY0OZhs1lKDEboPVUNvef1LbKDVuFMHIslHapact2sDvSu2ppgGCI6yD/0bOom3MxNt5d0kT2b5f3ERcp8X4dAo6leEwaez+6TqFqwUiLS6oodMtlsnZrvFW5aUiYZ4TIiaPCLlniHlYsenA6FDgKvGoP4Vf8jyA11wxHn5SGLzDtYmgL9xESj+V7GN684x3VpoSwuvXXt1W0Te6PdQMUs9GgzuWVho0AQ7gAg0wFbvcKXKCoEfpsbY8kU/Lgg+RiiPYismLpWbpTGcgl80HFooVPe9sTZg==","appId":"wx154f9a63aef2864f","signType":"RSA","nonceStr":"e3e56a34a8254b24a1924801d685cbb8"}"
		echojson([],1,'支付下单失败');
		//创建支付订单结束

	}
	public function getNoticeList2(){
		$where = " cid=224 and status=1 and uid=0";
		$list = getpagedata($this->tables->article,"id,title,title2,addTime",true,$where);
		$res = $list[0];
		$count = $list[1];
		$res = $res->all();
		foreach ($res as $k=>$v){
			$res[$k]['addTime']=date("m-d",strtotime($v['addTime']));
		}
		pagejson($res,0,'',$count);
	}
	public function getArticleInfo()
	{
		$id = request()->param("id");
		$order = DB::name($this->tables->article)->where("id",$id)->find();
		if (!$order) {
			echojson([], 1, 'ID错误');
		}
		if ($order['files'] != '') {
			$order['files'] = explode(",", $order['files']);
		} else {
			$order["files"] = [];
		}
		$order['files'] = imgAndHttp($order['files']);
		DB::name($this->tables->article)->where("id", $id)->inc("points")->update();
		echojson($order);
	}
	public function postFeedBack()
	{
		$content = request()->param("content");
		$mobile = request()->param("mobile");
		$ctype = request()->param("ctype");
		$upArr = ['uid' => $this->userID, 'addTime' => nowTime(), 'ctype' => $ctype, 'content' => $content, 'mobile' => $mobile];
		if ($content == '' || strlen($mobile) == '' || $ctype == '') {
			echojson([], 1, '所有不可为空');
		}
		$re = DB::name($this->tables->feedBack)->where("uid", $this->userID)->order("id desc")->find();
		if ($re) {
			if (time() - strtotime($re['addTime']) < 3600) {
				echojson([], 1, '需间隔一小时以上');
			}
		}
		$up = DB::name($this->tables->feedBack)->insert($upArr);
		if (!$up) {
			echojson([], 1, "提交失败");
		}
		echojson();
	}

	public function getOrderInfo()
	{
		$orderID = request()->param("orderID");
		$re = DB::name($this->tables->orders)->alias("a")->leftJoin($this->tables->gas." b","a.gasID=b.id")->field("a.reOrder,a.content,a.cause,a.id,a.order_no,a.oil_no,a.oil_gun,a.amount,a.sale,a.payPrice,a.volume,a.addTime,a.payJson,b.name,b.address,b.logo_small,a.status")->where("a.id",$orderID)->where("a.uid",$this->userID)->find();
		if (!$re)echojson([], 1, 'ID错误');
		$re['status'] = getOrderStatus($re['status']);
		if($re['reOrder']==-1)$re['status']="退款拒绝";
		if($re['reOrder']==1)$re['status']="退款中";
		if($re['reOrder']==2)$re['status']="退款完成";
		$re['payJson']=json_decode($re['payJson'],true);
		echojson($re);
	}
	public function getOrderList()
	{
		$page = request()->param("page");
		$sql = DB::name($this->tables->orders)->alias("a")->leftJoin($this->tables->gas." b","a.gasID=b.id")->field("a.id,a.order_no,a.gasID,a.oil_no,a.oil_gun,a.amount,a.sale,a.payPrice,a.volume,a.addTime,a.status,b.name,b.address,b.logo_small,b.status as bStatus")->where("a.uid", $this->userID)->where("a.status",">=",3);
		$page < 1 ? $page = 1 : '';
		$res = $sql->limit(($page - 1) * 10, 10)->order("a.id desc")->select();
		$res = $res->all();
		foreach ($res as &$v){
			$v['status']=getOrderStatus($v['status']);
		}
		echojson($res);
	}
	public function getGas(){
		$id = request()->param("id");
		$longitude = request()->param("longitude");
		$latitude = request()->param("latitude");
		if($longitude>0 && $latitude>0){
			$re = $this->getGasInfo($id,$longitude,$latitude);
			$re['distance2'] = $re['distance'];
			$re['distance'] = $this->setDistance($re['distance']);
		}else{
			$re = $this->getGasInfo($id);
		}
		$gasModel = new model\Gas();
		$gasModel->prices = $re['prices'];
		$re['prices'] = $gasModel->getWeekPrice();
		echojson($re);
	}
	public function getList(){
		$oil_no = request()->param("oil_no");
		$key = request()->param("key");
		$around = request()->param("around");
		$sort = request()->param("sort");
		$longitude = request()->param("longitude");
		$latitude = request()->param("latitude");
		if($oil_no=='')$oil_no="92#";
		$where="a.localStatus=1 and b.oil_no='$oil_no'";

		$page=request()->param("page");
		$limit=request()->param("limit");
		$page<1?$page=1:'';
		$limit<1?$limit=10:'';
		if($longitude>0 && $latitude>0){
			$addField=",(st_distance(point(a.lat,a.lng),point($latitude,$longitude))*111195) as distance";
			$order="distance asc";
		}else{
			$addField="";
			$order="a.id desc";
		}
		//[['value'=>0,'name'=>'智能排序'],['value'=>1,'name'=>'距离最近'],['value'=>2,'name'=>'单价最低'],['value'=>3,'name'=>'优惠最大']],
		if($sort>1){
			$order = "b.price_yfq asc,b.id desc";
		}
		$res = DB::name($this->tables->gas)->alias("a")->field("a.*,a.id as aid,b.*$addField")->leftJoin($this->tables->gasPrice." b","a.id=b.gasID")->where($where)->order($order)->limit((($page-1)*$limit),$limit);
		if($key!=''){
			$res = $res->where("a.name","like","%$key%");
		}
		if($around>0 && $longitude>0 && $latitude>0){
			$res = $res->having("distance<=$around");
		}
		$res = $res->select();
		$res = $res->all();
		foreach ($res as &$v){
			$gasModel = new model\Gas($v['aid'],[],$v);
			$gasModel->getGasPrice(true);//计算出所有价格
			$priceArr = $gasModel->getWeekPrice();// 根据当前周几计算价格

//			var_dump($priceArr);
//			exit();
			foreach ($priceArr as $v2){
				if($v2['oil_no'] == $oil_no)$v['price_yfq'] = $v2['price_yfq'];
			}
			$v['tips'][]="加200省".$this->calcSubMoney($v);
			$service = explode(",",$v['service']);
			if(count($service)>0 && $service[0]!='')$v['tips'][]=$service[0];
			if(count($service)>1 && $service[1]!='')$v['tips'][]=$service[1];
			$v['id']=$v['aid'];
			if($longitude>0 && $latitude>0){
				$v['distance2'] = $v['distance'];
				$v['distance'] = $this->setDistance($v['distance']);
			}

		}
		echojson($res);
	}
	protected function getGasInfo($id=0,$longitude='',$latitude=''){
		$gas = DB::name($this->tables->gas)->where("id",$id)->find();
		if($gas['fromID']==2){
			$model = new \app\controller\model\Supplier(2);
			$model->getGases($gas['gasID']);
		}
		$addField="";
		if($longitude>0 && $latitude>0){
			$addField=",(st_distance(point(lat,lng),point($latitude,$longitude))*111195) as distance";
		}
		$re = DB::name($this->tables->gas)->field("*$addField")->where("id",$id)->where('localStatus',1)->find();
		if(!$re)echojson([],1,'油站错误');
		$gasModel = new model\Gas($re['id'],[],$re);
		$re['prices']=$gasModel->getGasPrice(true);
		return $re;
	}
	protected function setDistance($num=0){
		if($num<1000){
			return $num."m";
		}else{
			return bcdiv($num,1000,1)."km";
		}
	}
	protected function calcSubMoney($re=[],$num=200){
		$L = bcdiv($num,$re['price_gun'],2);
		$money = bcmul($L,$re['price_yfq'],2);
		return bcsub($num,$money);
	}
	protected function check_token(){
		$this->token==""?$this->token=request()->param("token"):'';
		if(strlen($this->token)!=32){echojson([],401,"需登录");}
		$re=DB::name($this->tables->users)->where("token",$this->token)->find();
		if($re){
			if($re['status']<0){
				echojson([],1,$re['content']);
			}else{
				$this->user=$re;
				$this->userID=$re['id'];
				return true;
			}
		}else{
			echojson([],100,"验证错误");
		}
	}
	public function wxLogin(){
		//微信小程序登录
		$appId = $this->tables->wxAppID; // 替换为你的 AppID
		$appSecret = $this->tables->secret; // 替换为你的 AppSecret
		$code = request()->param("code");
		// 构建请求 URL
		$url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$appSecret&js_code=$code&grant_type=authorization_code";
		// 发起 HTTP 请求
		$response = file_get_contents($url);
		$data = json_decode($response, true);
		if (isset($data['errcode'])) {
			// 处理错误
			echojson([
				'success' => false,
				'message' => $data['errmsg']
			],1,'登录失败');
		}
		$user = DB::name($this->tables->users)->where("openid",$data['openid'])->find();
		if($user)echojson(['token'=>$user['token']]);
		// 返回 session_key 和 openid
		$up = ['openid'=>$data['openid'],'access_token'=>$data['session_key'],'addTime'=>nowTime(),'token'=>md5($data['openid'])] ;
		$userid = DB::name("users")->insertGetId($up);
		if($userid>0){
			echojson(['token'=>md5($data['openid'])]);
		}else{
			echojson([],1,'创建账户错误');
		}
	}

	public function getConfig(){
		$res = DB::name($this->tables->banner)->field("id,title,img,title2")->where("cid",213)->select();
		$res = $res->all();
		foreach ($res as $k => $v) {
			$res[$k]['url'] = apiURLHTTP() . apiURL() . $v['img'];
		}
		$reArr=[
			'banner'=>$res,
			'aroundArr'=>[['value'=>0,'name'=>'附近'],['value'=>500,'name'=>'500米内'],['value'=>1000,'name'=>'1千米内'],['value'=>3000,'name'=>'3千米内'],['value'=>10000,'name'=>'10千米内']],
			'sortArr'=>[['value'=>0,'name'=>'智能排序'],['value'=>1,'name'=>'距离最近'],['value'=>2,'name'=>'单价最低'],['value'=>3,'name'=>'优惠最大']],
			'mobile'=>'028-44444444'
		];
		echojson($reArr);
	}
}
